﻿<?php

class Book
{

//book data
	public $fileName;
	public $pureFileName;
	public $fileSize;

	public $book_title;
	public $authorName = array() ;
	public $translatorName = array() ;
	public $genre = array();
	public $annotation;
	public $date;
	public $coverpage;
	public $lang;
	public $srcLang;
	public $keywords;
	public $sequence = array();
	public $binary;

//publisher data
	public $publisherBookName;
	public $publisherPublisher;
	public $publisherCity;
	public $publisherYear;
	public $publisherISBN;

	public $FB_ERROR = array();




	public function readDataFromFile($filename)
	{
		$this->fileName = $filename;
		$this->pureFileName = basename($this->fileName) ;
		$this->fileSize = filesize($this->fileName);
        //Создаем XML документ
		$fb2XML = new DOMDocument();
        //Отключаем проверку ошибок
		$fb2XML->strictErrorChecking = false; $fb2XML->recover = true;

        // GZip check
		if (strcmp(mb_substr($this->fileName,-3,3),".gz") == 0)
        {
            $currentBookData = gzfile($this->fileName);
            $currentBookData = implode($currentBookData);
            $loadedFB2 =  $fb2XML->loadXML($currentBookData,LIBXML_NOERROR);
            $this->pureFileName = mb_substr($this->pureFileName,0,-3);
        }
        else
        {
            //Загружаем содиржоме файла
    		$loadedFB2 = $fb2XML->load($this->fileName,LIBXML_NOERROR);
    		$this->pureFileName = mb_substr($this->pureFileName,0,-4);

        }


			if (!$loadedFB2)
			{
				$this->FB_ERROR[] = "FILE: file load error" ;
			}



		//$this->binary = $fb2XML->getElementsByTagName('binary')->item(0)->nodeValue;
		//echo '<html><img src="data:image/gif;base64,' . base64_decode($this->binary) . '" /></html>';

		//Получаем содержимое секции <description>
		$description = $fb2XML->getElementsByTagName('description');
		$description = $description->item(0);
			if (!$description)
			{
				$this->FB_ERROR[] = "FB2 error: description section not found" ;
			}


		//Получаем название книги
		// TITLE (title_info)
		$title_info = $description->getElementsByTagName('title-info')->item(0);

		if (isset($title_info->getElementsByTagName('book-title')->item(0)->nodeValue))
		{
			$this->book_title = $title_info->getElementsByTagName('book-title')->item(0)->nodeValue;
		}
		else
		{
			$this->FB_ERROR[] = "FB2 error: Book title not found" ;
		}



		//получаем "файл нэйм" обложки
		// Specs sais it's always starts with # so drop it.
		$coverPageFileName = ltrim($title_info->getElementsByTagName('coverpage')->item(0)->getElementsByTagName('image')->item(0)->attributes->item(0)->nodeValue, "#");

		//$pureFileName;

		//Получаем обложку, картинку
		foreach ($fb2XML->getElementsByTagName('binary') as $currentPic)
		{
			foreach ($currentPic->attributes as $curAttr)
			{
				//search for attribute = id in case to found cover image that was pointed from <coverpage> tag
				if (strcasecmp($curAttr->nodeName,"id") == 0 )
				{
					// check if current binary, id is cover page.
					if (strcasecmp($curAttr->nodeValue, $coverPageFileName) == 0 )
					{
						$this->binary = $currentPic->nodeValue;
					}

				}

			}
		}




		//Получаем список жанров, к которым относится книга
		// GENRE
		$genre_list = $title_info->getElementsByTagName('genre');
		if ($genre_list->length==0)
		{
			$this->FB_ERROR[] = "FB2 error: genre not found" ;

		}
		else
		foreach ($genre_list as $currentGenre)
		{
			//Помещаем список жанров в массив
			$this->genre[] = $currentGenre->nodeValue;
		}

		//Получаем название серии и номер
//SEQUENCE
		$sequenceList = $description->getElementsByTagName('sequence');

		if (!$sequenceList)
		{
			$this->$sequence[0]['name']="" ;
			$this->$sequence[0]['number']="" ;
			$this->FB_ERROR[] = "FB2 warning: sequence not found" ;
		}
		else
		{
			$counter=0;
			foreach ($sequenceList as $currentSequence)
			{
				//Помещаем список серий в массив [порядковый номер][название]="название серии" / [порядковый номер][номер]="номер книги в серии"
				$this->sequence[$counter]['name'] = $currentSequence->getAttribute('name');
				$this->sequence[$counter]['number'] = $currentSequence->getAttribute('number');
				$counter++;
			}
		}

		//Получаем список авторов.
//AUTHOR
		$authors_list = $title_info->getElementsByTagName('author');
		if ($authors_list->length==0)
		{
			$this->FB_ERROR[] = "FB2 error: author not found" ;
		}
		else
		{
			$counter=0;

			foreach ($authors_list as $currentAuthor)
			{
				$this->authorName[$counter]['first_name'] =  (isset( $currentAuthor->getElementsByTagName('first-name')->item(0)->nodeValue) ?  $currentAuthor->getElementsByTagName('first-name')->item(0)->nodeValue : "");
				$this->authorName[$counter]['middle-name'] =  (isset( $currentAuthor->getElementsByTagName('middle-name')->item(0)->nodeValue) ?  $currentAuthor->getElementsByTagName('middle-name')->item(0)->nodeValue : "");
				$this->authorName[$counter]['last-name'] =  (isset( $currentAuthor->getElementsByTagName('last-name')->item(0)->nodeValue) ?  $currentAuthor->getElementsByTagName('last-name')->item(0)->nodeValue : "");
				$this->authorName[$counter]['nickname'] = (isset($currentAuthor->getElementsByTagName('nickname')->item(0)->nodeValue) ? $currentAuthor->getElementsByTagName('nickname')->item(0)->nodeValue : "" ) ;
				$this->authorName[$counter]['email'] =  (isset($currentAuthor->getElementsByTagName('email')->item(0)->nodeValue) ? $currentAuthor->getElementsByTagName('email')->item(0)->nodeValue : "" ) ;
				$counter++;
			}
		}

		//Получаем список переводчиков.
//TRANSLATOR
		$translators_list = $title_info->getElementsByTagName('translator');
		if ($translators_list->length==0)
		{
			$this->FB_ERROR[] = "FB2 warning: translator not found" ;
		}
		else
		{
			$counter=0;
			foreach ($translators_list as $currentTranslator)
			{
				$this->translatorName[$counter]['first_name'] = (isset( $currentTranslator->getElementsByTagName('first-name')->item(0)->nodeValue) ?  $currentTranslator->getElementsByTagName('first-name')->item(0)->nodeValue : "") ;
				$this->translatorName[$counter]['middle_name'] = (isset( $currentTranslator->getElementsByTagName('middle_name')->item(0)->nodeValue) ?  $currentTranslator->getElementsByTagName('middle_name')->item(0)->nodeValue : "") ;
				$this->translatorName[$counter]['last_name'] = (isset( $currentTranslator->getElementsByTagName('last_name')->item(0)->nodeValue) ?  $currentTranslator->getElementsByTagName('last_name')->item(0)->nodeValue : "") ;
				$this->translatorName[$counter]['nickname'] = (isset( $currentTranslator->getElementsByTagName('nickname')->item(0)->nodeValue) ?  $currentTranslator->getElementsByTagName('nickname')->item(0)->nodeValue : "") ;
				$this->translatorName[$counter]['email'] = (isset( $currentTranslator->getElementsByTagName('email')->item(0)->nodeValue) ?  $currentTranslator->getElementsByTagName('email')->item(0)->nodeValue : "") ;
				$counter++;

			}
		}

		//Получаем анотацию.
//ANNOTATION
		if ($title_info->getElementsByTagName('annotation')->length==0)
		{
			$this->FB_ERROR[] = "FB2 warning: annotation not found" ;
		}
		else
		{
			$this->annotation = trim($title_info->getElementsByTagName('annotation')->item(0)->nodeValue," \t\n\r\0\x0B");
		}



		//Получаем дату.
//DATE
		if ($title_info->getElementsByTagName('date')->length==0)
		{
			$this->FB_ERROR[] = "FB2 warning: date not found" ;
		}
		else
		{
			$this->date = $title_info->getElementsByTagName('date')->item(0)->nodeValue;
		}

		//Получаем язык.
//LANGUAGE
		if ($title_info->getElementsByTagName('lang')->length==0)
		{
			$this->FB_ERROR[] = "FB2 warning: language not found" ;
		}
		else
		{
			$this->lang = $title_info->getElementsByTagName('lang')->item(0)->nodeValue;
		}

		//Получаем язык оригинала.
//SOURCE_LANGUAGE
		if ($title_info->getElementsByTagName('src-lang')->length==0)
		{
			$this->FB_ERROR[] = "FB2 warning: language of source not found" ;
		}
		else
		{
			$this->srcLang = $title_info->getElementsByTagName('src-lang')->item(0)->nodeValue;
		}

		//Получаем keywords.
//KEYWORDS
		if ($title_info->getElementsByTagName('keywords')->length==0)
		{
			$this->FB_ERROR[] = "FB2 warning: keywords not found" ;
		}
		else
		{
			$this->keywords = $title_info->getElementsByTagName('keywords')->item(0)->nodeValue;
		}


// PUBLISH(ER)-INFO

		$publish_info = $description->getElementsByTagName('publish-info')->item(0);

		if (!$publish_info)
		{
			$this->FB_ERROR[] = "FB2 warning: publisher info was found";
		}
		else
		{
			$this->publisherBookName = $publish_info->getElementsByTagName('book-name')->item(0)->nodeValue;
			$this->publisherPublisher = $publish_info->getElementsByTagName('publisher')->item(0)->nodeValue;
			$this->publisherCity = $publish_info->getElementsByTagName('city')->item(0)->nodeValue;
			$this->publisherYear = $publish_info->getElementsByTagName('year')->item(0)->nodeValue;
			$this->publisherISBN = $publish_info->getElementsByTagName('isbn')->item(0)->nodeValue;
		}



	}






	public function getBookDataFromDB($bookID)
	{
		$query = "call findByID($bookID)";

		$result = mysqli_query($connection, $query) ;

		while($row = mysqli_fetch_array($result))
		{
			var_dump($row);
		}

	}


}

/*
 $counter = 0;

foreach ($tmp->binary as $currentPic)
{

	$file = fopen("img/test_".$counter.".jpg", 'wb') ;
	fwrite($file, base64_decode($currentPic));
	fclose($file);
	$counter++;
}

 */

// $tmp = new Book;

// $tmp->readDataFromFile("knig/Tolstoy_Voyna-i-mir_3_Voyna-i-mir-Tom-3.175746.fb2") ;

//  print_r ($tmp);


?>
